<template>
  <div class="md-area-cascader-business">
    <el-cascader ref="mdAreaCascaderBusiness" style="width: 100%" v-model="codes" :options="options" :placeholder="placeholder" @change="handleChange"></el-cascader>
  </div>
</template>

<script>
export default {
  name: 'MdAreaCascaderBusinessComponent',
  props: {
    value: [Array, Object],
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data () {
    return {
      codes: [],
      options: []
    }
  },
  watch: {
    value: {
      handler (val) {
        this.codes = val.filter(e => e)
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.options = this.getAreaTreeData(this.$local.getItem('area'), '0')
  },
  methods: {
    /** 获取树数据 */
    getAreaTreeData (data, pid) {
      const result = []

      data.forEach(item => {
        item.value = item.areaCode
        item.label = item.areaName

        if (item.parentAreaCode === pid) {
          const children = this.getAreaTreeData(data, item.areaCode)
          if (children.length > 0) {
            item.children = children
          }
          result.push(item)
        }
      })

      return result
    },
    /** 选择区域改变事件 */
    handleChange (event) {
      this.$emit('input', event)

      this.$nextTick(() => {
        setTimeout(() => {
          const areaRef = this.$refs.mdAreaCascaderBusiness
          if (areaRef.inputValue) {
            const areaTexts = areaRef.inputValue.split(areaRef.separator)

            this.$emit('change', { codes: event, texts: areaTexts })
          }
        }, 200)
      })
    }
  }
}
</script>
